package com.hzhc.utils;

import cn.hutool.core.io.resource.ResourceUtil;
import lombok.extern.log4j.Log4j2;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: YmlUtil
 * @Description:
 * @version 1.0
 * @author: duanhm
 * @Date: 2024/07/24 14:26:16
 * 
 */
@Log4j2
public class YmlUtil {
	@SuppressWarnings("unchecked")
	public void updateYamlFileTest() throws IOException {
		List<URL> resources = ResourceUtil.getResources("application.yml");
		// Resource app = new ClassPathResource("config/application.yml");
		URL resource = resources.get(0);
		System.out.println("====" + resource);
		String src = resource.getFile();
		// this.getClass().getClassLoader().getResource("application.yaml").getPath();
		Yaml yaml = new Yaml();
		FileWriter fileWriter;
		FileInputStream fileInputStream = new FileInputStream(new File(src));
		Map<String, Object> yamlMap = yaml.load(fileInputStream);

		Map<String, Object> esMap = (Map<String, Object>) yamlMap.get("sensitive");
		esMap.put("enable", false);
		// 字符输出
		fileWriter = new FileWriter(new File(src));
		// 用yaml方法把map结构格式化为yaml文件结构
		fileWriter.write(yaml.dumpAsMap(yamlMap));
		// 刷新
		fileWriter.flush();
		// 关闭流
		fileWriter.close();
		fileInputStream.close();
	}

	@SuppressWarnings("unchecked")
	public static void updateYaml(String fileName, String key, Object value) {
		try {
			Map<String, Object> yamlMap = (Map<String, Object>) loadYaml(fileName);
			if (key.contains(".")) {
				String[] keyall = key.split("\\.");
				Map<String, Object> esMap = null;
				for (int i = 0; i < keyall.length; i++) {
					log.info(keyall[i]);
					if (i == (keyall.length - 1)) {
						esMap.put(keyall[i], value);
					} else {
						esMap = (Map<String, Object>) yamlMap.get(keyall[i]);
					}

				}
			} else {
				// Map<String, Object> esMap = (Map<String, Object>) yamlMap.get(key);
				yamlMap.put(key, value);
			}

			Yaml yaml = new Yaml();
			FileWriter fileWriter;
			String src = getFilePath(fileName);
			FileInputStream fileInputStream = new FileInputStream(new File(src));
			// Map<String, Object> yamlMap = yaml.load(fileInputStream);

			// Map<String, Object> esMap = (Map<String, Object>) yamlMap.get("sensitive");
			// esMap.put("enable", false);
			// 字符输出
			fileWriter = new FileWriter(new File(src));
			// 用yaml方法把map结构格式化为yaml文件结构
			fileWriter.write(yaml.dumpAsMap(yamlMap));
			// 刷新
			fileWriter.flush();
			// 关闭流
			fileWriter.close();
			fileInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static LinkedHashMap<?, ?> loadYaml(String fileName) throws Exception {
		String filepath = "";
		String path = System.getProperty("user.dir");
		filepath = path + "/config/" + fileName;
		File file = new File(filepath);
		InputStream in;
		if (file.exists()) {
			in = new FileInputStream(filepath);
		} else {
			// TODO 如果没有config文件夹，则从项目的resources目录下找
			List<URL> resources = ResourceUtil.getResources("application.yml");
			URL resource = resources.get(0);
			filepath = resource.getFile();
			in = YmlUtil.class.getClassLoader().getResourceAsStream(fileName);
		}
		log.info("filepath=={}", filepath);
		LinkedHashMap<?, ?> lhm = new Yaml().loadAs(in, LinkedHashMap.class);
		return lhm;
	}

	public static String getFilePath(String fileName) throws Exception {
		String filepath = "";
		String path = System.getProperty("user.dir");
		filepath = path + "/config/" + fileName;
		File file = new File(filepath);
		if (file.exists()) {

		} else {
			// TODO 如果没有config文件夹，则从项目的resources目录下找
			List<URL> resources = ResourceUtil.getResources(fileName);
			URL resource = resources.get(0);
			log.info("resource=={}", resource);
			filepath = resource.getFile();
		}
		log.info("filepath=={}", filepath);
		return filepath;
	}

	public static Object getValByKey(Map<?, ?> lhm, String key) throws Exception {
		String[] keys = key.split("[.]");
		Map<?, ?> ymlInfo = lhm;
		for (int i = 0; i < keys.length; i++) {
			Object value = ymlInfo.get(keys[i]);
			if (i < keys.length - 1) {
				ymlInfo = (Map<?, ?>) value;
			} else if (value == null) {
				throw new Exception("key不存在");
			} else {
				return value;
			}
		}

		return null;
	}

}
